"use strict"

function rr(color) {
  var colors = [0x2cbab2, 0x47a700, 0xd60000, 0x087f87, 0x37ad0e, 0x4d4d4d, 0xce7e00, 0xe0a213, 0x87bcde]
  var index = Math.floor(Math.random() * colors.length)

  this.color = color || colors[index]
  this.mesh = new THREE.Object3D()
  this.wheels = []
  this.startAngle = 0

  var that = this
  addBody()
  addLights() //光

  function addLights() {
    var carLightsGeometry = new THREE.Geometry()
    carLightsGeometry = new THREE.BufferGeometry().fromGeometry(carLightsGeometry)
    var carLights = utils.makeMesh('phong', carLightsGeometry, 0xffffff)
    that.mesh.add(carLights)
  }

  function addBody() {
    var lamp = new THREE.Object3D()
    var pillarGeomertry = new THREE.CubeGeometry(2, 30, 2)
    pillarGeomertry.translate(0, 15, 0)
    var pillar = utils.makeMesh('lambert', pillarGeomertry, 0xebd1c2)
    lamp.add(pillar)

    // var connectGeometry = new THREE.CubeGeometry(10, 1, 1)
    // var connect = utils.makeMesh('lambert', connectGeometry, 0x2c0e0e)
    // connect.position.set(3, 30, 0)
    // lamp.add(connect)

    that.mesh.add(lamp)

  }

}

rr.prototype = {
  setPosition: function(x, y, z) {
    this.mesh.position.set(x, y, z)
  },
  forward: function(speed) {
    var speed = speed || 1
    this._moving(speed, true)
  },
  backward: function(speed) {
    var speed = speed || 1
    this._moving(speed, false)
  },
  turnLeft: function(angle, speed) {
    this._turn(angle, true, speed)
  },
  turnRight: function(angle, speed) {
    this._turn(angle, false, speed)
  },
  _turn: function(angle, direction, speed) {
    var direction = direction ? 1 : -1
    if (speed) {
      if (this.startAngle < angle) {
        this.mesh.rotation.y += speed
        this.startAngle += speed
        if (angle - this.startAngle < speed) {
          var originAngle = this.mesh.rotation.y - this.startAngle
          this.mesh.rotation.y = originAngle + angle
          this.startAngle = 0
          return
        }
      }
    } else {
      this.mesh.rotation.y += angle * direction
    }
  },
  _moving: function(speed, direction) {
    speed = speed/2;
    var rotation = this.mesh.rotation.y
    var direction = direction ? 1 : -1
    var xLength = speed * Math.cos(rotation) * direction,
      zLength = speed * Math.sin(rotation) * direction
    this.mesh.position.x += xLength/2
    this.mesh.position.z -= zLength/2
    // this._rotateWheels(speed)
  },
  // _rotateWheels: function(speed) {
  //   this.wheels.forEach(function(elem) {
  //     elem.rotation.z -= 0.1 * speed/2
  //   })
  // }
}
